
File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
import pandas as pd
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import plotly.express as px
import plotly.io as pio
from itertools import cycle
import numpy as np
import os
df = pd.read_csv('data/서울시 외로움 정도(UCLA).csv')
index = pd.MultiIndex.from_frame(df.iloc[:,:2])
# there is a bug in pandas when its using multi index to create a DataFrame
# below is to circumvent that
# its seems you can not feed DataFrame directly and it causes pandas to create Nan values....
data = df.to_numpy()[:,-3:]
column_names = df.columns.values.tolist()
df = pd.DataFrame(data, index=index, columns=column_names[-3:])
# data and colors
columns = df.columns[2:]
palette = cycle(px.colors.qualitative.Alphabet)
# palette = cycle(px.colors.sequential.PuBu)
colors = {c:next(palette) for c in columns}
tex = index.to_list()
for i, t in enumerate(tex):
tex[i] = " ".join(t)
# subplot setup
fig = make_subplots(
rows=3, cols=1,
subplot_titles= ['',''],
)
legend = ['외로움', '보통', '외롭지 않음']
c = ['#E6000F', '#FFCA08', '#3DF05B']
for chart, row in enumerate(df.groupby(level=0)):
for i, cols in enumerate(range(np.shape(data)[1])):
# groupby returns ('the name of index that has beens sliced', DataFrame)
# shouldn't that be the first thing that should be mentioned in the reference?...
tex = row[1].index.to_list()
data = row[1].to_numpy()[:,-3:]
for g, t in enumerate(tex):
tex[g] = t[1]
fig.add_trace(
go.Bar(
y=tex, # the x axis
x=data[:,i], # the value you stack
name = legend[i], #name of each bar
marker=dict(
color= c[i]
) ,
# marker_color = ['#DE4954', '#A7004C', '#57D3FC'],
# legendgroup = cols,
# marker_color = colors[cols],
showlegend = True if chart == 0 else False,
orientation = 'h'
),
row = chart+1, col = 1
)
fig.update_xaxes(range=[0,100])
fig.update_yaxes(dtick=1)
fig.update_layout(barmode='stack')
fig.update_layout(
# title="서울시 1인가구 외로움 정도 (UCLA 외로움 척도)",
font_size= 55,
)
fig.update_layout(
font=dict({'family': 'KoPubDotum'})
)
fig.update_annotations(font_size=100)
fig.update_traces(texttemplate="%{x:.3s}%")
fig.update_layout(uniformtext_minsize=20, uniformtext_mode= 'hide')
fig.update_layout(
yaxis=dict(
domain=[0,0.23]
),
yaxis2 = dict(
domain=[0.27, 0.66],
),
yaxis3 = dict(
domain=[0.70, 1]
),
xaxis2=dict(
showticklabels=False
),
xaxis3=dict(
showticklabels =False
),
legend=dict(
traceorder='reversed'
),
plot_bgcolor= 'rgba(0,0,0,0)'
)
fig.update_layout(
# margin =dict(
# t=0,
# b=500
# ),
legend = dict(
bgcolor = 'rgba(0,0,0,0)',
itemwidth= 100,
orientation = 'h',
xanchor = "right",
yanchor = "bottom",
x = 0.8, y= -0.2,
traceorder='reversed'
),
margin=dict(
# t=400
)
)
fig.show()
pio.write_image(fig, "서울시 1인가구 외로움 정도.png", format="png", scale=3, width=2000, height=1200)